<template>
  <div class="notice-list">
    <!-- 页面标题和操作区域 -->
    <el-card class="header-card">
      <div class="page-header">
        <h2>通知列表</h2>
        <el-button type="primary" @click="handleCreate" icon="Plus" v-if="hasPermission('notice:create')">
          发布通知
        </el-button>
      </div>
    </el-card>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入公告标题" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="草稿" value="DRAFT" />
            <el-option label="已发布" value="PUBLISHED" />
            <el-option label="已下线" value="ARCHIVED" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable style="width: 150px">
            <el-option label="普通" value="GENERAL" />
            <el-option label="考试" value="EXAM" />
            <el-option label="系统" value="SYSTEM" />
            <el-option label="紧急" value="URGENT" />
          </el-select>
        </el-form-item>
        <el-form-item label="置顶">
          <el-select v-model="searchForm.isTop" placeholder="是否置顶" clearable style="width: 150px">
            <el-option label="是" value="true" />
            <el-option label="否" value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="紧急">
          <el-select v-model="searchForm.isUrgent" placeholder="是否紧急" clearable style="width: 150px">
            <el-option label="是" value="true" />
            <el-option label="否" value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="Search">搜索</el-button>
          <el-button @click="handleReset" icon="Refresh">重置</el-button>
          <el-button type="success" @click="fetchData" icon="RefreshRight">刷新</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card>
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="content-cell">{{ row.content }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creatorUsername" label="发布人" width="120" />
        <el-table-column prop="publishTime" label="发布时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)" icon="View">查看</el-button>
            <el-button link type="primary" @click="handleEdit(row)" v-if="hasPermission('notice:edit')" icon="Edit">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)" v-if="hasPermission('notice:delete')" icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { usePermission } from '@/composables/usePermission'
import { noticeApi } from '@/api/notice'
import type { Notice } from '@/types'

const router = useRouter()
const { hasPermission } = usePermission()

const loading = ref(false)
const tableData = ref<Notice[]>([])

const searchForm = ref({
  title: '',
  status: '',
  type: '',
  isTop: '',
  isUrgent: ''
})

const pagination = ref({
  page: 1,
  size: 10,
  total: 0
})

const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    DRAFT: 'info',
    PUBLISHED: 'success',
    ARCHIVED: 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    DRAFT: '草稿',
    PUBLISHED: '已发布',
    ARCHIVED: '已下线'
  }
  return texts[status] || status
}

const fetchData = async () => {
  loading.value = true
  try {
    const response = await noticeApi.getNotices({
      page: pagination.value.page - 1,
      size: pagination.value.size,
      ...searchForm.value
    })
    tableData.value = response.data.content
    pagination.value.total = response.data.totalElements
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.value.page = 1
  fetchData()
}

const handleReset = () => {
  searchForm.value = { title: '', status: '' }
  handleSearch()
}

const handleCreate = () => {
  router.push('/notices/create')
}

const handleView = (row: Notice) => {
  router.push(`/notices/${row.id}`)
}

const handleEdit = (row: Notice) => {
  router.push(`/notices/${row.id}/edit`)
}

const handleDelete = async (row: Notice) => {
  try {
    await ElMessageBox.confirm('确定要删除这条公告吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await noticeApi.deleteNotice(row.id!)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSizeChange = () => {
  fetchData()
}

const handleCurrentChange = () => {
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.notice-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.content-cell {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 1.5;
}
</style>